package com.kaiwukj.android.ufamily.mvp.ui.page.service.gm.playback;

import android.os.Bundle;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.mvp.http.entity.helper.EzVideoPlaybackEntity;
import com.kaiwukj.android.ufamily.mvp.http.entity.helper.GMDeviceInfo;
import com.kaiwukj.android.ufamily.mvp.ui.widget.RefreshLayout;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.bean.EZDeviceRecordFile;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

@Route(path = ARouterUrlKt.GMVideoPlayBackList)
public class GMOrderVideoPlayBackListActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.refresh_layout)
    RefreshLayout mRefreshLayout;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.empty_view)
    QMUIEmptyView emptyView;

    private PlaybackListParentAdapter mListAdapter;


    @Autowired
    GMDeviceInfo deviceInfo;

    @OnClick(R.id.container_left)
    void onBackClick() {
        onBackPressedSupport();
    }

    @Override
    protected int getLayoutId() {
        ARouter.getInstance().inject(this);
        return R.layout.activity_list_normal;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvTitle.setText("回放列表");

        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setEnableRefresh(false);
        rvList.setLayoutManager(new LinearLayoutManager(this));
        rvList.setNestedScrollingEnabled(true);
        mListAdapter = new PlaybackListParentAdapter();
        rvList.setAdapter(mListAdapter);

        mListAdapter.setItemListener((position, file) -> {
            ARouter.getInstance().build(ARouterUrlKt.GMVideoPlayBack)
                    .withSerializable("deviceInfo", deviceInfo)
                    .withParcelable("playbackFile", file)
                    .navigation();
        });

    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        long nowMs = System.currentTimeMillis();
        long startMs = nowMs - 7 * 24 * 60 * 60 * 1000;
        Calendar startTime = Calendar.getInstance();
        startTime.setTimeInMillis(startMs);
        Calendar endTime = Calendar.getInstance();
        endTime.setTimeInMillis(nowMs);
        emptyView.show(true);
        subscribe(Observable.create((ObservableOnSubscribe<List<EZDeviceRecordFile>>) emitter -> {
            emitter.onNext(EZOpenSDK.getInstance().searchRecordFileFromDevice(deviceInfo.getDeviceSerial(), deviceInfo.getCameraNo(), startTime, endTime));
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(results -> {
                    //LogUtils.d("tmpList------------------>" + GsonUtils.toJson(group(results)));
                    emptyView.hide();
                    onGetPlayList(group(results));
                }, e -> {
                    LogUtils.e(e.getCause());
                    emptyView.hide();
                }));
    }


    private List<EzVideoPlaybackEntity> group(List<EZDeviceRecordFile> results) {

        Collections.sort(results, (o1, o2) -> {
            long d1 = o1.getStartTime().getTimeInMillis();
            long d2 = o2.getStartTime().getTimeInMillis();
            return Long.compare(d2, d1);
        });

        //LogUtils.d("sort------------------->" + GsonUtils.toJson(results));

        List<EzVideoPlaybackEntity> groupResult = new ArrayList<>();

        Map<String, List<EZDeviceRecordFile>> tmpMap = new HashMap<>();

        for (EZDeviceRecordFile result : results) {
            String groupTitle = TimeUtils.millis2String(result.getStartTime().getTimeInMillis(), "yyyy.MM.dd");
            List<EZDeviceRecordFile> tmpList = tmpMap.get(groupTitle);
            if (tmpList == null) {
                tmpList = new ArrayList<>();
                tmpList.add(result);
                tmpMap.put(groupTitle, tmpList);
            } else {
                tmpList.add(result);
            }
        }

        for (Map.Entry<String, List<EZDeviceRecordFile>> entry : tmpMap.entrySet()) {
            EzVideoPlaybackEntity entity = new EzVideoPlaybackEntity();
            entity.setGroupTitle(entry.getKey());
            entity.setResults(entry.getValue());
            groupResult.add(entity);
        }

        Collections.sort(groupResult, (o1, o2) -> {
            long d1 = TimeUtils.string2Millis(o1.getGroupTitle(), "yyyy.MM.dd");
            long d2 = TimeUtils.string2Millis(o2.getGroupTitle(), "yyyy.MM.dd");
            return Long.compare(d2, d1);
        });

        return groupResult;

    }

    private void onGetPlayList(List<EzVideoPlaybackEntity> data) {
        mListAdapter.setList(data);
        if (mListAdapter.getItemCount() == 0) {
            emptyView.show("暂没有数据", "");
        }
    }

}
